package org.azj.dbOperatorComponent;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

public class TransactionManager implements ITransaction
{
    private DataSource dataSource;

    public TransactionManager(DataSource dataSource)
    {
        this.dataSource = dataSource;
    }

    @Override
    public void start() throws SQLException
    {
        Connection connection = getConnection();
        connection.setAutoCommit(false);
    }

    @Override
    public void commit() throws SQLException
    {
        Connection connection = getConnection();
        connection.commit();
    }

    @Override
    public void rollback()
    {
        Connection connection = null;
        try
        {
            connection = getConnection();
            connection.rollback();

        } catch (SQLException e)
        {
            throw new RuntimeException("Couldn't rollback on connection[" + connection + "].", e);
        }
    }

    @Override
    public void close()
    {
        Connection connection = null;
        try
        {
            connection = getConnection();
            connection.setAutoCommit(true);
            connection.setReadOnly(false);
            connection.close();
            SingleThreadConnectionHolder.removeConnection(dataSource);
        } catch (SQLException e)
        {
            throw new RuntimeException("Couldn't close connection[" + connection + "].", e);
        }
    }

    @Override
    public DataSource getDataSource()
    {
        return dataSource;
    }
    
    private Connection getConnection() throws SQLException
    {
    	return SingleThreadConnectionHolder.getConnection(dataSource);
    }
}